<template>
  <div class="product-container">
    <div class="page-header">
      <h1 class="page-title">产品管理</h1>
      <p class="page-description">管理医疗产品和服务项目</p>
    </div>

    <div class="content-area">
      <!-- 搜索筛选区域 -->
      <div class="filter-container">
        <div class="filter-form">
          <div class="filter-item">
            <label class="filter-label">产品名称</label>
            <el-input
              v-model="searchForm.title"
              placeholder="请输入产品名称"
              clearable
              size="default"
              class="filter-input"
            />
          </div>

          <div class="filter-item">
            <label class="filter-label">分类</label>
            <el-select
              v-model="searchForm.category"
              placeholder="请选择分类"
              clearable
              filterable
              size="default"
              class="filter-select"
              :empty-text="
                categories.length === 0 ? '暂无分类数据' : '无匹配数据'
              "
            >
              <el-option
                v-for="category in categories"
                :key="category.id"
                :label="category.name"
                :value="category.name"
              />
            </el-select>
          </div>

          <div class="filter-item">
            <label class="filter-label">价格范围</label>
            <div class="price-range">
              <el-input
                v-model="searchForm.minPrice"
                placeholder="最低价"
                type="number"
                size="default"
                class="price-input"
              />
              <span class="price-divider">-</span>
              <el-input
                v-model="searchForm.maxPrice"
                placeholder="最高价"
                type="number"
                size="default"
                class="price-input"
              />
            </div>
          </div>


          <div class="filter-item">
            <el-button type="primary" @click="handleSearch" size="default" class="search-btn">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset" size="default" class="reset-btn"> 重置 </el-button>
          </div>
        </div>
      </div>

      <!-- 操作按钮区域 -->
      <div class="action-section">
        <div class="action-left">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增产品
          </el-button>
          <el-button
            type="danger"
            :disabled="selectedRows.length === 0"
            @click="handleBatchDelete"
          >
            <el-icon><Delete /></el-icon>
            批量删除 ({{ selectedRows.length }})
          </el-button>
          <el-button type="warning" @click="handleDownloadTemplate">
            <el-icon><Download /></el-icon>
            下载导入模板
          </el-button>
          <el-button type="success" @click="handleBatchImport">
            <el-icon><Upload /></el-icon>
            批量导入
          </el-button>
          <el-button type="info" @click="handleExport">
            <el-icon><Download /></el-icon>
            导出数据
          </el-button>
        </div>
        <div class="action-right">
          <el-select
            v-model="searchForm.sortBy"
            placeholder="排序字段"
            size="default"
            style="width: 120px; margin-right: 8px"
            @change="handleSortChange"
          >
            <el-option label="创建时间" value="createTime" />
            <el-option label="价格" value="price" />
            <el-option label="浏览量" value="viewCount" />
            <el-option label="评分" value="rating" />
          </el-select>
          <el-select
            v-model="searchForm.sortOrder"
            placeholder="排序方式"
            size="default"
            style="width: 100px"
            @change="handleSortChange"
          >
            <el-option label="降序" value="desc" />
            <el-option label="升序" value="asc" />
          </el-select>
        </div>
      </div>

      <!-- 隐藏的Excel导入导出组件 -->
      <ExcelImportExporter
        ref="excelImporterRef"
        :data="allData"
        :columns="excelColumns"
        :filename="`产品数据_${new Date().toLocaleDateString()}`"
        :show-download-template="false"
        @import-success="handleImportSuccess"
        @import-error="handleImportError"
        @export-start="() => ElMessage.info('开始导出数据...')"
        @export-success="() => ElMessage.success('产品数据导出成功！')"
        @export-error="() => ElMessage.error('导出失败，请重试')"
        style="display: none;"
      />
      
      <!-- 隐藏的文件输入元素用于导入 -->
      <input
        ref="fileInputRef"
        type="file"
        accept=".xlsx,.xls"
        style="display: none"
        @change="handleFileImport"
      />

      <!-- 数据表格 -->
      <div class="table-section">
        <el-table
          :data="visibleData"
          :loading="loading"
          border
          stripe
          height="100%"
          @scroll="handleTableScroll"
          @selection-change="handleSelectionChange"
          ref="tableRef"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column label="产品图片" width="90">
            <template #default="scope">
              <el-image
                v-if="scope.row.image"
                :src="scope.row.image"
                :alt="scope.row.title"
                style="width: 50px; height: 50px"
                fit="cover"
                :preview-src-list="[scope.row.image]"
                :preview-teleported="true"
              >
                <template #placeholder>
                  <div
                    style="
                      display: flex;
                      align-items: center;
                      justify-content: center;
                      width: 100%;
                      height: 100%;
                      background-color: #f5f7fa;
                      color: #909399;
                    "
                  >
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
                <template #error>
                  <div
                    style="
                      display: flex;
                      align-items: center;
                      justify-content: center;
                      width: 100%;
                      height: 100%;
                      background-color: #f5f7fa;
                      color: #909399;
                    "
                  >
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column prop="title" label="产品名称" width="220" />
          <el-table-column prop="category" label="分类" width="130">
            <template #default="scope">
              <el-tag type="primary">
                {{ scope.row.category || "-" }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="评分" width="175">
            <template #default="scope">
              <RatingDisplay :value="scope.row.rating" />
            </template>
          </el-table-column>
          <el-table-column label="价格" width="130">
            <template #default="scope">
              <div>
                <div style="color: #e74c3c; font-weight: bold">
                  ¥{{ scope.row.price?.toLocaleString() || 0 }}
                </div>
                <div
                  v-if="scope.row.originalPrice"
                  style="
                    color: #999;
                    text-decoration: line-through;
                    font-size: 12px;
                  "
                >
                  ¥{{ scope.row.originalPrice.toLocaleString() }}
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="优惠" width="110">
            <template #default="scope">
              <div
                v-if="scope.row.saved && scope.row.saved > 0"
                style="color: #e74c3c; font-weight: bold"
              >
                省¥{{ scope.row.saved?.toLocaleString() || 0 }}
              </div>
              <span v-else style="color: #999">暂无优惠</span>
            </template>
          </el-table-column>
          <el-table-column prop="viewCount" label="浏览量" width="100" />
          <el-table-column label="创建时间" width="220">
            <template #default="scope">
              {{ formatDate(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button size="small" @click="handleView(scope.row)"
                >查看</el-button
              >
              <el-button size="small" @click="handleEdit(scope.row)"
                >编辑</el-button
              >
              <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑产品弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑产品' : '新增产品'"
      width="800px"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="productFormRef"
        :model="productForm"
        :rules="productRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品名称" prop="title">
              <el-input
                v-model="productForm.title"
                placeholder="请输入产品名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类" prop="category">
              <div style="display: flex; gap: 8px; align-items: flex-start">
                <el-select
                  v-model="productForm.category"
                  placeholder="请选择分类"
                  clearable
                  filterable
                  style="flex: 1"
                  :empty-text="
                    categories.length === 0 ? '暂无分类数据' : '无匹配数据'
                  "
                >
                  <el-option
                    v-for="category in categories"
                    :key="category.id"
                    :label="category.name"
                    :value="category.id"
                  />
                </el-select>
                <el-button
                  @click="showAddCategoryDialog = true"
                  type="primary"
                  plain
                >
                  新增分类
                </el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="当前价格" prop="price">
              <el-input-number
                v-model="productForm.price"
                :min="0"
                :precision="0"
                :step="100"
                placeholder="请输入价格"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="原价">
              <el-input-number
                v-model="productForm.originalPrice"
                :min="0"
                :precision="0"
                :step="100"
                placeholder="请输入原价"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="省市区域">
              <el-cascader
                v-model="productForm.regionCascader"
                :options="regionOptions"
                :props="cascaderProps"
                placeholder="请选择省份/城市"
                style="width: 100%"
                @change="handleProductRegionChange"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="关联医院">
              <div style="display: flex; gap: 8px; align-items: flex-start">
                <el-select
                  v-model="selectedHospitalIds"
                  placeholder="请选择医院（可多选）"
                  filterable
                  multiple
                  collapse-tags
                  :max-collapse-tags="2"
                  style="flex: 1"
                  @change="handleHospitalSelect"
                >
                  <el-option
                    v-for="h in hospitalOptions"
                    :key="h.id"
                    :label="`${h.name}${
                      h.address ? '（' + h.address + '）' : ''
                    }`"
                    :value="h.id"
                  />
                </el-select>
                <el-button
                  @click="showHospitalDetails = !showHospitalDetails"
                  type="primary"
                  plain
                >
                  {{ showHospitalDetails ? "隐藏详情" : "查看详情" }}
                </el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 医院详情配置 -->
        <el-row
          v-if="showHospitalDetails && productForm.hospitals.length > 0"
          :gutter="20"
        >
          <el-col :span="24">
            <el-form-item label="医院详情">
              <div class="hospital-details-container">
                <div
                  v-for="(hospital, index) in productForm.hospitals"
                  :key="hospital.hospitalId"
                  class="hospital-detail-item"
                >
                  <div class="hospital-header">
                    <span class="hospital-name">{{
                      hospital.hospitalName
                    }}</span>
                    <el-switch
                      v-model="hospital.isActive"
                      active-text="启用"
                      inactive-text="禁用"
                    />
                  </div>
                  <div class="hospital-pricing">
                    <el-input-number
                      v-model="hospital.price"
                      :min="0"
                      :precision="0"
                      placeholder="特定价格"
                      size="small"
                      style="width: 120px; margin-right: 8px"
                    />
                    <el-input-number
                      v-model="hospital.originalPrice"
                      :min="0"
                      :precision="0"
                      placeholder="特定原价"
                      size="small"
                      style="width: 120px"
                    />
                  </div>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="产品标签">
              <div style="display: flex; gap: 8px; align-items: flex-start">
                <el-select
                  v-model="productForm.tags"
                  multiple
                  filterable
                  collapse-tags
                  :max-collapse-tags="3"
                  :multiple-limit="3"
                  placeholder="最多选择3个标签"
                  style="flex: 1"
                >
                  <el-option
                    v-for="item in tagOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.name"
                  />
                </el-select>
                <el-button @click="openNewTagDialog" type="primary" plain
                  >新增标签</el-button
                >
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="产品图片" prop="images">
              <el-upload
                :http-request="uploadRequest"
                name="file"
                list-type="picture-card"
                :limit="9"
                :file-list="imageFileList"
                :on-remove="handleUploadRemove"
                :on-preview="handlePreview"
                :on-exceed="handleUploadExceed"
                accept="image/*"
                multiple
                :class="{ 'upload-max-reached': imageFileList.length >= 9 }"
              >
                <div v-if="imageFileList.length < 9" class="upload-trigger">
                  <el-icon><Plus /></el-icon>
                </div>
              </el-upload>
              <div class="upload-tip">
                支持上传多张图片，最多9张，建议尺寸800x600像素
                <span v-if="imageFileList.length > 0" class="upload-count">
                  (已上传 {{ imageFileList.length }}/9 张)
                </span>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 新增标签弹窗 -->
      <el-dialog v-model="newTagDialogVisible" title="新增标签" width="400px">
        <el-input
          v-model="newTagName"
          placeholder="请输入标签名称"
          maxlength="20"
          show-word-limit
        />
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="newTagDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleCreateTag">保存</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 新增分类弹窗 -->
      <el-dialog v-model="showAddCategoryDialog" title="新增分类" width="400px">
        <el-form
          :model="categoryForm"
          :rules="categoryRules"
          ref="categoryFormRef"
          label-width="80px"
        >
          <el-form-item label="分类名称" prop="name">
            <el-input
              v-model="categoryForm.name"
              placeholder="请输入分类名称"
              maxlength="50"
              show-word-limit
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="handleCancelAddCategory">取消</el-button>
            <el-button
              type="primary"
              @click="handleCreateCategory"
              :loading="categorySubmitting"
            >
              {{ categorySubmitting ? "创建中..." : "保存" }}
            </el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 图片预览查看器 -->
      <el-image-viewer
        v-if="previewDialogVisible"
        :url-list="[previewImageUrl]"
        :initial-index="0"
        @close="previewDialogVisible = false"
      />

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button
            type="primary"
            @click="handleSubmit"
            :loading="submitLoading"
          >
            {{ isEdit ? "更新" : "创建" }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 产品详情查看对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="产品详情"
      width="800px"
      :close-on-click-modal="false"
    >
      <div v-if="currentProduct" class="product-detail">
        <!-- 基本信息 -->
        <div class="detail-section">
          <h3 class="section-title">基本信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="产品名称">
              {{ currentProduct.title }}
            </el-descriptions-item>
            <el-descriptions-item label="产品分类">
              {{ getProductCategoryName(currentProduct.category) }}
            </el-descriptions-item>
            <el-descriptions-item label="当前价格">
              <span style="color: #e74c3c; font-weight: bold; font-size: 16px">
                ¥{{ currentProduct.price?.toLocaleString() || 0 }}
              </span>
            </el-descriptions-item>
            <el-descriptions-item label="原价">
              <span
                v-if="currentProduct.originalPrice"
                style="color: #999; text-decoration: line-through"
              >
                ¥{{ currentProduct.originalPrice.toLocaleString() }}
              </span>
              <span v-else>-</span>
            </el-descriptions-item>
            <el-descriptions-item label="优惠金额">
              <span
                v-if="currentProduct.saved && currentProduct.saved > 0"
                style="color: #e74c3c; font-weight: bold"
              >
                省¥{{ currentProduct.saved.toLocaleString() }}
              </span>
              <span v-else>暂无优惠</span>
            </el-descriptions-item>
            <el-descriptions-item label="评分">
              <RatingDisplay :value="currentProduct.rating" size="default" />
            </el-descriptions-item>
            <el-descriptions-item label="浏览量">
              {{ currentProduct.viewCount || 0 }}
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">
              {{ formatDate(currentProduct.createTime) }}
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 产品图片 -->
        <div
          v-if="getProductImages(currentProduct).length > 0"
          class="detail-section"
        >
          <h3 class="section-title">
            产品图片 ({{ getProductImages(currentProduct).length }}张)
          </h3>
          <div class="images-container">
            <el-image
              v-for="(imageUrl, index) in getProductImages(currentProduct)"
              :key="index"
              :src="getFullImageUrl(imageUrl)"
              :preview-src-list="getProductImages(currentProduct).map((url: string) => getFullImageUrl(url))"
              :initial-index="index"
              fit="cover"
              style="
                width: 120px;
                height: 120px;
                border-radius: 8px;
                border: 1px solid #dcdfe6;
                margin-right: 12px;
                margin-bottom: 12px;
              "
              :preview-teleported="true"
            >
              <template #error>
                <div class="image-slot">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
          </div>
        </div>

        <!-- 产品标签 -->
        <div
          v-if="currentProduct.tags && currentProduct.tags.length > 0"
          class="detail-section"
        >
          <h3 class="section-title">产品标签</h3>
          <div class="tags-container">
            <el-tag
              v-for="tag in currentProduct.tags"
              :key="tag"
              type="primary"
              style="margin-right: 8px; margin-bottom: 8px"
            >
              {{ tag }}
            </el-tag>
          </div>
        </div>

        <!-- 关联医院 -->
        <div
          v-if="currentProduct.hospitals && currentProduct.hospitals.length > 0"
          class="detail-section"
        >
          <h3 class="section-title">关联医院</h3>
          <el-table :data="currentProduct.hospitals" border style="width: 100%">
            <el-table-column prop="hospitalName" label="医院名称" />
            <el-table-column label="价格" width="120">
              <template #default="scope">
                <span
                  v-if="scope.row.price"
                  style="color: #e74c3c; font-weight: bold"
                >
                  ¥{{ scope.row.price.toLocaleString() }}
                </span>
                <span v-else
                  >¥{{ currentProduct.price?.toLocaleString() || 0 }}</span
                >
              </template>
            </el-table-column>
            <el-table-column label="原价" width="120">
              <template #default="scope">
                <span
                  v-if="scope.row.originalPrice"
                  style="color: #999; text-decoration: line-through"
                >
                  ¥{{ scope.row.originalPrice.toLocaleString() }}
                </span>
                <span
                  v-else-if="currentProduct.originalPrice"
                  style="color: #999; text-decoration: line-through"
                >
                  ¥{{ currentProduct.originalPrice.toLocaleString() }}
                </span>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column label="状态" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.isActive ? 'success' : 'danger'">
                  {{ scope.row.isActive ? "启用" : "禁用" }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="添加时间" width="180">
              <template #default="scope">
                {{
                  scope.row.addedTime ? formatDate(scope.row.addedTime) : "-"
                }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleEditFromDetail"
            >编辑产品</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, nextTick } from "vue";
import { ElMessage, ElMessageBox, ElImageViewer } from "element-plus";
import {
  Plus,
  Upload,
  Download,
  Search,
  Refresh,
  Picture,
  Delete,
} from "@element-plus/icons-vue";
import request from "@/utils/request";
import { provinceAndCityData } from "element-china-area-data";
import RatingDisplay from "@/views/datalist/Component/rating/RatingDisplay.vue";
import ExcelImportExporter from "@/components/ExcelImportExporter.vue";

// 定义接口类型
interface Product {
  _id: string;
  title: string; // 商品标题/名称
  price: number; // 基础价格（元）
  originalPrice?: number; // 基础原价（元）
  saved?: number; // 基础节省金额（元）
  hospitals?: Array<{
    // 关联的医院列表
    hospitalId: string;
    hospitalName: string;
    price?: number;
    originalPrice?: number;
    isActive: boolean;
    addedTime?: string;
  }>;
  hospitalId?: string; // 向后兼容字段
  rating?: number; // 评分（如4.8分）
  tags?: string[]; // 商品标签数组
  image?: string; // 主要商品图片URL（向后兼容）
  images?: string[]; // 商品图片URL数组（支持多图片）
  category: string; // 商品分类
  // isHot?: boolean               // 是否热门商品（字段已废弃）
  viewCount?: number; // 浏览次数
  createTime: string; // 创建时间
}

interface SearchForm {
  title: string;
  category: string;
  minPrice: string;
  maxPrice: string;
  sortBy: string;
  sortOrder: string;
}

interface Pagination {
  currentPage: number;
  pageSize: number;
  total: number;
}

interface ApiResponse<T> {
  success: boolean;
  data: T;
  pagination?: {
    page: number;
    limit: number;
    total: number;
    pages: number;
  };
  message?: string;
}

// 响应式数据
const loading = ref(false);
const loadingMore = ref(false);
const allData = ref<Product[]>([]); // 存储所有数据
const tableRef = ref();
const currentLoadedPage = ref(0); // 当前已加载的页数
const selectedRows = ref<Product[]>([]); // 选中的行数据

const searchForm = reactive<SearchForm>({
  title: "",
  category: "",
  minPrice: "",
  maxPrice: "",
  sortBy: "createTime",
  sortOrder: "desc",
});

const categories = ref<{ id: string; name: string }[]>([]);
const tagOptions = ref<{ id: string; name: string }[]>([]);

// Excel导入导出相关
const excelImporterRef = ref();

// Excel列配置
interface ExcelColumn {
  key: string;
  title: string;
  width?: number;
  formatter?: (value: any, row: any) => string;
  validator?: (value: any) => boolean | string;
  required?: boolean;
}

const excelColumns: ExcelColumn[] = [
  {
    key: "title",
    title: "产品名称",
    width: 25,
    required: true,
    validator: (value: any) => {
      if (!value || value.toString().trim() === "") {
        return "产品名称不能为空";
      }
      if (value.toString().length > 100) {
        return "产品名称不能超过100个字符";
      }
      return true;
    },
  },
  {
    key: "category",
    title: "产品分类",
    width: 15,
    required: true,
    validator: (value: any) => {
      if (!value || value.toString().trim() === "") {
        return "产品分类不能为空";
      }
      // 导入时允许使用分类名称，导入处理时会自动转换为ID
      if (value.toString().length > 50) {
        return "产品分类名称不能超过50个字符";
      }
      return true;
    },
  },
  {
    key: "price",
    title: "价格（元）",
    width: 12,
    required: true,
    formatter: (value: number) => value?.toString() || "0",
    validator: (value: any) => {
      if (value === undefined || value === null || value === "") {
        return "价格不能为空";
      }
      const num = Number(value);
      if (isNaN(num)) {
        return "价格必须是有效数字";
      }
      if (num < 0) {
        return "价格必须大于等于0";
      }
      return true;
    },
  },
  {
    key: "originalPrice",
    title: "原价（元）",
    width: 12,
    formatter: (value: number) => value?.toString() || "",
    validator: (value: any) => {
      if (
        value === undefined ||
        value === null ||
        value === "" ||
        value === "0"
      )
        return true;
      const num = Number(value);
      if (isNaN(num)) {
        return "原价必须是有效数字";
      }
      if (num < 0) {
        return "原价必须大于等于0";
      }
      return true;
    },
  },
  {
    key: "rating",
    title: "评分（1-5）",
    width: 12,
    formatter: (value: number) => value?.toString() || "5.0",
    validator: (value: any) => {
      if (
        value === undefined ||
        value === null ||
        value === "" ||
        value === "0"
      )
        return true;
      const num = Number(value);
      if (isNaN(num)) {
        return "评分必须是有效数字";
      }
      if (num < 0 || num > 5) {
        return "评分必须是0-5之间的数字";
      }
      return true;
    },
  },
  {
    key: "viewCount",
    title: "浏览量",
    width: 12,
    formatter: (value: number) => value?.toString() || "0",
    validator: (value: any) => {
      if (
        value === undefined ||
        value === null ||
        value === "" ||
        value === "0"
      )
        return true;
      const num = Number(value);
      if (isNaN(num)) {
        return "浏览量必须是有效数字";
      }
      if (num < 0) {
        return "浏览量必须大于等于0";
      }
      if (!Number.isInteger(num)) {
        return "浏览量必须是整数";
      }
      return true;
    },
  },
  {
    key: "tags",
    title: "标签（用逗号分隔）",
    width: 20,
    formatter: (value: string[]) =>
      Array.isArray(value) ? value.join(",") : value || "",
    validator: (value: any) => {
      if (value === undefined || value === null || value === "") return true;

      // 处理字符串形式的标签（逗号分隔）
      if (typeof value === "string") {
        const tags = value
          .split(",")
          .map((tag) => tag.trim())
          .filter((tag) => tag);
        if (tags.length > 5) {
          return "标签数量不能超过5个";
        }
        for (const tag of tags) {
          if (tag.length > 20) {
            return "单个标签长度不能超过20个字符";
          }
        }
      }
      return true;
    },
  },
  {
    key: "image",
    title: "产品图片URL",
    width: 30,
    validator: (value: any) => {
      if (value === undefined || value === null || value === "") return true;

      const url = value.toString().trim();
      if (!url) return true;

      // 更宽松的URL验证，支持相对路径和绝对路径
      const isValidUrl =
        url.startsWith("http://") ||
        url.startsWith("https://") ||
        url.startsWith("/uploads/") ||
        url.includes("localhost") ||
        /\.(jpg|jpeg|png|gif|webp)$/i.test(url);

      if (!isValidUrl) {
        return "请输入有效的图片URL或路径";
      }
      return true;
    },
  },
];

// 弹窗相关
const dialogVisible = ref(false);
const isEdit = ref(false);
const submitLoading = ref(false);

// 详情查看相关
const detailDialogVisible = ref(false);
const currentProduct = ref<Product | null>(null);
const editingProductId = ref<string>("");
const productFormRef = ref();
const tagInputVisible = ref(false);
const tagInputValue = ref("");
const tagInputRef = ref();

// 医院联动
const hospitalOptions = ref<{ id: string; name: string; address?: string }[]>(
  []
);
const selectedHospitalIds = ref<string[]>([]); // 改为数组支持多选
const showHospitalDetails = ref(false); // 控制医院详情显示

// 产品表单数据
const productForm = reactive({
  title: "",
  category: "",
  price: 0,
  originalPrice: 0,
  saved: 0,
  hospitals: [] as Array<{
    hospitalId: string;
    hospitalName: string;
    price?: number;
    originalPrice?: number;
    isActive: boolean;
  }>,
  rating: 5.0,
  tags: [] as string[],
  image: "",
  images: [] as string[],
  // isHot: false,
  viewCount: 0,
  regionCascader: [] as string[],
});

// 用于筛选医院的省市数据（仅用于筛选，不存储）
const hospitalFilterForm = reactive({
  province: "",
  city: "",
});

// 表单验证规则
// 表单不做规则校验

// 级联选择器配置
const cascaderProps = {
  value: "value",
  label: "label",
  children: "children",
  emitPath: false,
  checkStrictly: true,
};

// 使用npm包的省市数据
const regionOptions = ref(provinceAndCityData);

const pagination = reactive<Pagination>({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

// 计算属性
const visibleData = computed(() => {
  const startIndex = (pagination.currentPage - 1) * pagination.pageSize;
  const endIndex = startIndex + pagination.pageSize;
  return allData.value.slice(startIndex, endIndex);
});

const needsMoreData = computed(() => {
  const currentPageData = (pagination.currentPage - 1) * pagination.pageSize;
  return (
    currentPageData + pagination.pageSize > allData.value.length &&
    allData.value.length < pagination.total
  );
});

// 工具函数
const formatDate = (dateString: string) => {
  if (!dateString) return "-";
  const date = new Date(dateString);
  return date.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
  });
};

// 搜索处理
const handleSearch = () => {
  pagination.currentPage = 1;
  allData.value = [];
  currentLoadedPage.value = 0;
  fetchData();
};

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    title: "",
    category: "",
    minPrice: "",
    maxPrice: "",
    sortBy: "createTime",
    sortOrder: "desc",
  });
  handleSearch();
};

// 排序改变处理
const handleSortChange = () => {
  handleSearch();
};

// 新增产品
const handleAdd = () => {
  isEdit.value = false;
  resetProductForm();
  // 确保医院选项数据是最新的
  fetchHospitalsByRegion();
  dialogVisible.value = true;
};

// 查看产品详情
const handleView = (row: Product) => {
  currentProduct.value = row;
  detailDialogVisible.value = true;
};

// 从详情页面编辑产品
const handleEditFromDetail = async () => {
  if (currentProduct.value) {
    detailDialogVisible.value = false;
    await handleEdit(currentProduct.value);
  }
};

// 获取产品分类名称
const getProductCategoryName = (category: any) => {
  if (!category) return "-";

  // 如果是对象，直接返回name
  if (typeof category === "object" && category.name) {
    return category.name;
  }

  // 如果是字符串ID，在分类列表中查找
  if (typeof category === "string") {
    const categoryItem = categories.value.find(
      (cat) => cat.id === category || cat.name === category
    );
    return categoryItem ? categoryItem.name : category;
  }

  return "-";
};

// 获取完整图片URL
const getFullImageUrl = (imageUrl: string) => {
  if (!imageUrl) return "";
  if (imageUrl.startsWith("http")) return imageUrl;
  const baseURL = import.meta.env.VITE_API_BASE_URL || "http://localhost:3000";
  return `${baseURL}${imageUrl}`;
};

// 获取产品图片数组（优先使用images，兼容image）
const getProductImages = (product: any) => {
  if (!product) return [];

  // 优先使用images数组
  if (
    product.images &&
    Array.isArray(product.images) &&
    product.images.length > 0
  ) {
    return product.images;
  }

  // 兼容单张图片
  if (product.image) {
    return [product.image];
  }

  return [];
};

// 编辑产品
const handleEdit = async (row: Product) => {
  console.log("=== 开始编辑产品 ===");
  console.log("原始产品数据:", JSON.stringify(row, null, 2));
  isEdit.value = true;
  editingProductId.value = row._id;
  console.log("设置编辑ID:", editingProductId.value);

  // 确保分类列表已加载
  if (categories.value.length === 0) {
    console.log("分类列表为空，重新加载...");
    await fetchCategories();
  }
  console.log("当前分类列表:", categories.value);

  fillProductForm(row);
  dialogVisible.value = true;
  console.log("编辑模式设置完成");
};

// 处理表格选择变化
const handleSelectionChange = (selection: Product[]) => {
  selectedRows.value = selection;
};

// 删除产品
const handleDelete = async (row: Product) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除产品 "${row.title}" 吗？此操作不可撤销！`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: false,
      }
    );

    const response = (await request.delete(
      `/pccosmetic/products/${row._id}`
    )) as any;

    if (response.success) {
      ElMessage.success("删除成功");
      // 刷新数据但保持分页状态
      await refreshData();
    } else {
      ElMessage.error(response.message || "删除失败");
    }
  } catch (error: any) {
    if (error === "cancel") {
      ElMessage.info("已取消删除");
    } else {
      console.error("删除产品失败:", error);
      ElMessage.error(error.response?.data?.message || "删除失败");
    }
  }
};

// 批量删除产品
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请先选择要删除的产品");
    return;
  }

  try {
    const productTitles = selectedRows.value.map((row) => row.title).join("、");
    const confirmMessage =
      selectedRows.value.length === 1
        ? `确定要删除产品 "${productTitles}" 吗？此操作不可撤销！`
        : `确定要删除选中的 ${selectedRows.value.length} 个产品吗？此操作不可撤销！\n\n产品列表：${productTitles}`;

    await ElMessageBox.confirm(confirmMessage, "确认批量删除", {
      confirmButtonText: "确定删除",
      cancelButtonText: "取消",
      type: "warning",
      dangerouslyUseHTMLString: false,
    });

    const ids = selectedRows.value.map((row) => row._id);
    const response = (await request.delete("/pccosmetic/products/batch", {
      data: { ids },
    })) as any;

    if (response.success) {
      ElMessage.success(`成功删除 ${response.deletedCount} 个产品`);
      // 清空选择
      selectedRows.value = [];
      // 刷新数据但保持分页状态
      await refreshData();
    } else {
      ElMessage.error(response.message || "批量删除失败");
    }
  } catch (error: any) {
    if (error === "cancel") {
      ElMessage.info("已取消删除");
    } else {
      console.error("批量删除产品失败:", error);
      ElMessage.error(error.response?.data?.message || "批量删除失败");
    }
  }
};

// 导出数据
const handleExport = async () => {
  try {
    if (allData.value.length === 0) {
      ElMessage.warning("暂无数据可导出");
      return;
    }

    // 使用Excel导出组件
    await excelImporterRef.value?.export();
  } catch (error) {
    console.error("导出失败:", error);
    ElMessage.error("导出失败，请重试");
  }
};

// 批量导入成功处理
const handleImportSuccess = async (data: any[]) => {
  try {
    ElMessage.info(`开始导入 ${data.length} 条产品数据...`);

    // 确保分类数据已加载
    if (categories.value.length === 0) {
      console.log("分类数据为空，重新加载...");
      await fetchCategories();
    }
    console.log("当前可用分类:", categories.value);

    let successCount = 0;
    let failCount = 0;
    const errors: string[] = [];

    for (let i = 0; i < data.length; i++) {
      const item = data[i];
      try {
        // 数据转换和处理
        let categoryId = item.category?.toString().trim();
        console.log(`第${i + 1}行：原始分类值 = "${categoryId}"`);

        // 将分类名称转换为分类ID
        if (categoryId) {
          const categoryItem = categories.value.find(
            (cat) => cat.name === categoryId || cat.id === categoryId
          );
          if (categoryItem) {
            const oldCategoryId = categoryId;
            categoryId = categoryItem.id;
            console.log(
              `第${i + 1}行：分类转换成功 "${oldCategoryId}" → "${categoryId}"`
            );
          } else {
            console.error(`第${i + 1}行：分类转换失败，未找到匹配的分类`);
            console.log(
              `可用分类列表:`,
              categories.value.map((cat) => `${cat.name}(${cat.id})`)
            );
            // 如果找不到匹配的分类，抛出错误
            throw new Error(
              `未找到分类"${categoryId}"，请确保分类名称正确或先创建该分类。当前可用分类：${categories.value
                .map((cat) => cat.name)
                .join(", ")}`
            );
          }
        }

        const productData: Partial<Product> = {
          title: item.title?.toString().trim(),
          category: categoryId,
          price: Number(item.price) || 0,
          originalPrice: item.originalPrice
            ? Number(item.originalPrice)
            : undefined,
          rating: item.rating ? Number(item.rating) : 5.0,
          viewCount: item.viewCount ? Number(item.viewCount) : 0,
          image: item.image?.toString().trim() || "",
          tags: item.tags
            ? typeof item.tags === "string"
              ? item.tags
                  .split(",")
                  .map((tag: string) => tag.trim())
                  .filter((tag: string) => tag)
              : Array.isArray(item.tags)
              ? item.tags
              : []
            : [],
        };

        // 计算节省金额
        if (
          productData.originalPrice &&
          productData.price &&
          productData.originalPrice > productData.price
        ) {
          productData.saved = productData.originalPrice - productData.price;
        }

        // 最终验证：确保category是有效的ObjectId格式
        if (productData.category) {
          const isValidObjectId = /^[0-9a-fA-F]{24}$/.test(
            productData.category
          );
          if (!isValidObjectId) {
            throw new Error(
              `分类ID格式不正确："${productData.category}"，应该是24位十六进制字符串`
            );
          }
        }

        console.log(`第${i + 1}行：准备提交的产品数据:`, productData);

        // 调用API创建产品
        const response = (await request.post(
          "/pccosmetic/products",
          productData
        )) as any;

        console.log(`第${i + 1}行：API完整响应:`, response);

        // 修复响应判断逻辑：request工具成功时直接返回后端数据对象
        if (response && response.success === true) {
          successCount++;
          console.log(`第${i + 1}行：创建成功`, response);
        } else {
          failCount++;
          console.error(`第${i + 1}行：创建失败`, response);
          errors.push(`第${i + 1}行: ${response?.message || "创建失败"}`);
        }
      } catch (error: any) {
        failCount++;
        errors.push(
          `第${i + 1}行: ${
            error.response?.data?.message || error.message || "导入失败"
          }`
        );
      }
    }

    // 显示导入结果
    if (successCount > 0) {
      ElMessage.success(
        `导入成功！成功导入 ${successCount} 条数据${
          failCount > 0 ? `，失败 ${failCount} 条` : ""
        }`
      );

      // 重置分页到第一页并刷新数据
      pagination.currentPage = 1;
      allData.value = [];
      currentLoadedPage.value = 0;
      await fetchData();
    } else {
      ElMessage.error("导入失败，没有成功导入任何数据");
    }

    // 如果有错误，显示详情
    if (errors.length > 0 && errors.length <= 10) {
      ElMessage.warning(
        `部分数据导入失败：\n${errors.slice(0, 5).join("\n")}${
          errors.length > 5 ? "\n..." : ""
        }`
      );
    }
  } catch (error: any) {
    console.error("批量导入失败:", error);
    ElMessage.error(`批量导入失败: ${error.message || "未知错误"}`);
  }
};

// 批量导入错误处理
const handleImportError = (error: any) => {
  console.error("导入失败:", error);
  ElMessage.error("文件导入失败，请检查文件格式");
};

// 下载导入模板
const handleDownloadTemplate = async () => {
  try {
    await excelImporterRef.value?.downloadTemplate();
    ElMessage.success("模板下载成功！");
  } catch (error) {
    console.error("下载模板失败:", error);
    ElMessage.error("下载模板失败，请重试");
  }
};

// 批量导入（触发文件选择）
const handleBatchImport = () => {
  fileInputRef.value?.click();
};

// 处理文件导入
const fileInputRef = ref();
const handleFileImport = async (event: Event) => {
  const target = event.target as HTMLInputElement;
  const files = target.files;
  if (!files || files.length === 0) return;
  
  const file = files[0];
  try {
    await excelImporterRef.value?.importFile(file);
  } catch (error) {
    console.error("文件导入失败:", error);
    ElMessage.error("文件导入失败，请重试");
  } finally {
    // 清空文件输入，允许重复选择同一文件
    target.value = '';
  }
};

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  allData.value = [];
  currentLoadedPage.value = 0;
  fetchData();
};

// 当前页改变
const handleCurrentChange = async (page: number) => {
  pagination.currentPage = page;

  // 检查是否需要加载更多数据
  if (needsMoreData.value) {
    await loadMoreData();
  }
};

// 加载更多数据
const loadMoreData = async () => {
  if (loadingMore.value || allData.value.length >= pagination.total) return;

  try {
    loadingMore.value = true;
    const nextPage = currentLoadedPage.value + 1;

    // 构建查询参数
    const params: any = {
      page: nextPage,
      limit: pagination.pageSize * 2, // 每次加载2页的数据
    };

    // 添加搜索条件
    if (searchForm.title.trim()) {
      params.title = searchForm.title.trim();
    }
    if (searchForm.category) {
      params.category = searchForm.category;
    }
    if (searchForm.minPrice) {
      params.minPrice = searchForm.minPrice;
    }
    if (searchForm.maxPrice) {
      params.maxPrice = searchForm.maxPrice;
    }
    if (searchForm.sortBy) {
      params.sortBy = searchForm.sortBy;
    }
    if (searchForm.sortOrder) {
      params.sortOrder = searchForm.sortOrder;
    }

    const response = (await request.get("/pccosmetic/products", {
      params,
    })) as ApiResponse<Product[]>;

    if (response.success && response.data.length > 0) {
      allData.value.push(...response.data);
      currentLoadedPage.value = nextPage;

      if (response.pagination) {
        pagination.total = response.pagination.total;
      }
    }
  } catch (error) {
    console.error("加载更多数据失败:", error);
    ElMessage.error("加载更多数据失败");
  } finally {
    loadingMore.value = false;
  }
};

// 获取产品分类
const fetchCategories = async () => {
  try {
    // 优先使用与产品创建API相同数据模型的分类API
    const response = (await request.get("/pcproductimg/categories/all")) as any;
    if (response.success && Array.isArray(response.data)) {
      categories.value = response.data.map((item: any) => ({
        id: item.id,
        name: item.name,
      }));
      console.log("✅ 成功获取分类数据（ProductTypeModel）:", categories.value);
      return; // 成功获取，直接返回
    }
  } catch (error) {
    console.error("获取ProductTypeModel分类失败:", error);
  }

  // 备选方案：尝试其他分类API
  try {
    const fallbackResponse = (await request.get(
      "/pccosmetic/products/categories"
    )) as ApiResponse<string[]>;
    if (fallbackResponse.success && Array.isArray(fallbackResponse.data)) {
      // 字符串格式的分类（这种格式与ProductTypeModel不兼容，仅作备选）
      categories.value = fallbackResponse.data.map((name: string) => ({
        id: name, // 注意：这不是真正的ObjectId
        name: name,
      }));
      console.log(
        "⚠️ 使用备选分类数据（字符串格式，可能导致创建失败）:",
        categories.value
      );
      ElMessage.warning("分类数据来源不匹配，建议检查分类管理功能");
    }
  } catch (fallbackError) {
    console.error("备选分类API也失败:", fallbackError);
    ElMessage.error("无法获取分类数据，请检查网络连接或联系管理员");
  }
};

// 获取数据
const fetchData = async () => {
  try {
    loading.value = true;

    // 构建查询参数
    const params: any = {
      page: 1,
      limit: pagination.pageSize * 2, // 初始加载2页数据
    };

    // 添加搜索条件
    if (searchForm.title.trim()) {
      params.title = searchForm.title.trim();
    }
    if (searchForm.category) {
      params.category = searchForm.category;
    }
    if (searchForm.minPrice) {
      params.minPrice = searchForm.minPrice;
    }
    if (searchForm.maxPrice) {
      params.maxPrice = searchForm.maxPrice;
    }
    if (searchForm.sortBy) {
      params.sortBy = searchForm.sortBy;
    }
    if (searchForm.sortOrder) {
      params.sortOrder = searchForm.sortOrder;
    }

    const response = (await request.get("/pccosmetic/products", {
      params,
    })) as ApiResponse<Product[]>;

    if (response.success) {
      allData.value = response.data;
      currentLoadedPage.value = 1;

      if (response.pagination) {
        pagination.total = response.pagination.total;
      }
    } else {
      ElMessage.error(response.message || "获取数据失败");
    }
  } catch (error) {
    console.error("获取产品数据失败:", error);
    ElMessage.error("获取数据失败");
  } finally {
    loading.value = false;
  }
};

// 刷新当前数据（保持分页状态）
const refreshData = async () => {
  try {
    loading.value = true;

    // 计算需要加载的页数以保持当前数据量
    const currentDataPages = Math.ceil(
      allData.value.length / pagination.pageSize
    );
    const loadPages = Math.max(currentDataPages, 1);

    // 构建查询参数
    const params: any = {
      page: 1,
      limit: pagination.pageSize * loadPages,
    };

    // 添加搜索条件
    if (searchForm.title.trim()) {
      params.title = searchForm.title.trim();
    }
    if (searchForm.category) {
      params.category = searchForm.category;
    }
    if (searchForm.minPrice) {
      params.minPrice = searchForm.minPrice;
    }
    if (searchForm.maxPrice) {
      params.maxPrice = searchForm.maxPrice;
    }
    if (searchForm.sortBy) {
      params.sortBy = searchForm.sortBy;
    }
    if (searchForm.sortOrder) {
      params.sortOrder = searchForm.sortOrder;
    }

    const response = (await request.get("/pccosmetic/products", {
      params,
    })) as ApiResponse<Product[]>;

    if (response.success) {
      allData.value = response.data;
      currentLoadedPage.value = loadPages;

      if (response.pagination) {
        pagination.total = response.pagination.total;
      }
    } else {
      ElMessage.error(response.message || "获取数据失败");
    }
  } catch (error) {
    console.error("刷新产品数据失败:", error);
    ElMessage.error("刷新数据失败");
  } finally {
    loading.value = false;
  }
};

// 表格滚动处理
const handleTableScroll = () => {
  // 可以在这里添加滚动到底部自动加载更多的逻辑
};

// 弹窗相关方法
const resetProductForm = () => {
  Object.assign(productForm, {
    title: "",
    category: "",
    price: 0,
    originalPrice: 0,
    saved: 0,
    hospitals: [],
    rating: 5.0,
    tags: [],
    image: "",
    images: [],
    // isHot: false,
    viewCount: 0,
    regionCascader: [],
  });

  // 重置图片上传列表
  imageFileList.value = [];

  // 重置医院筛选表单
  Object.assign(hospitalFilterForm, {
    province: "",
    city: "",
  });

  tagInputVisible.value = false;
  tagInputValue.value = "";
  selectedHospitalIds.value = [];
  hospitalOptions.value = [];
  showHospitalDetails.value = false;
  editingProductId.value = "";
  isEdit.value = false;
};

const fillProductForm = (product: Product) => {
  console.log("=== fillProductForm 开始 ===");
  console.log("输入的产品数据:", product);

  // 处理分类数据
  let categoryValue = null;
  console.log("原始分类数据类型:", typeof product.category);
  console.log("原始分类数据值:", product.category);

  if (typeof product.category === "object" && product.category !== null) {
    // populate后的分类对象，取_id
    categoryValue = (product.category as any)._id;
    console.log("从分类对象中提取_id:", categoryValue);
  } else if (typeof product.category === "string") {
    // 如果是字符串，需要判断是分类名称还是分类ID
    const isObjectId = /^[0-9a-fA-F]{24}$/.test(product.category);
    if (isObjectId) {
      // 是ObjectId格式的字符串，直接使用
      categoryValue = product.category;
      console.log("直接使用分类ID字符串:", categoryValue);
    } else {
      // 是分类名称，需要根据名称找到对应的ID
      const categoryItem = categories.value.find(
        (cat) => cat.name === product.category
      );
      if (categoryItem) {
        categoryValue = categoryItem.id;
        console.log(
          "根据分类名称找到对应的ID:",
          product.category,
          "->",
          categoryValue
        );
      } else {
        console.warn("未找到匹配的分类ID，分类名称:", product.category);
        console.log("当前分类列表:", categories.value);
        categoryValue = null;
      }
    }
  } else {
    console.log("分类数据为空或其他类型");
  }

  console.log("最终分类值:", categoryValue);

  Object.assign(productForm, {
    title: product.title,
    category: categoryValue,
    price: product.price,
    originalPrice: product.originalPrice || 0,
    saved: product.saved || 0,
    hospitals: (product as any).hospitals || [],
    rating: product.rating || 5.0,
    tags: product.tags || [],
    image: product.image || "",
    images: (product as any).images || (product.image ? [product.image] : []),
    // isHot: product.isHot || false,
    viewCount: 0,
    regionCascader: [],
  });

  // 设置图片文件列表用于回显（支持多图片）
  const imagesToShow =
    productForm.images.length > 0
      ? productForm.images
      : product.image
      ? [product.image]
      : [];

  if (imagesToShow.length > 0) {
    const baseURL =
      import.meta.env.VITE_API_BASE_URL || "http://localhost:3000";

    imageFileList.value = imagesToShow.map((imageUrl, index) => {
      const fullUrl = imageUrl.startsWith("http")
        ? imageUrl
        : `${baseURL}${imageUrl}`;
      return {
        name: `product-image-${index + 1}`,
        url: fullUrl,
        uid: Date.now() + index,
      };
    });
  } else {
    imageFileList.value = [];
  }

  // 设置选中的医院ID数组
  if ((product as any).hospitals && Array.isArray((product as any).hospitals)) {
    selectedHospitalIds.value = (product as any).hospitals.map(
      (h: any) => h.hospitalId
    );
  } else if (product.hospitalId) {
    // 向后兼容单个hospitalId
    selectedHospitalIds.value = [product.hospitalId];
  }

  // 加载全部医院列表（编辑时不再基于省市筛选）
  fetchHospitalsByRegion();

  console.log("=== fillProductForm 完成 ===");
  console.log("设置后的 productForm:", JSON.stringify(productForm, null, 2));
  console.log("设置后的 selectedHospitalIds:", selectedHospitalIds.value);
  console.log("设置后的 imageFileList:", imageFileList.value);
};

const handleDialogClose = () => {
  productFormRef.value?.resetFields();
  resetProductForm();
  dialogVisible.value = false;
};

const handleSubmit = async () => {
  try {
    console.log("=== 开始提交产品 ===");
    console.log("当前编辑模式:", isEdit.value);
    console.log("当前编辑ID:", editingProductId.value);
    console.log("当前表单数据:", JSON.stringify(productForm, null, 2));
    console.log("当前选中的医院IDs:", selectedHospitalIds.value);
    console.log("当前分类列表:", categories.value);

    await productFormRef.value?.validate();
    console.log("表单验证通过");

    submitLoading.value = true;

    // 计算节省金额
    if (productForm.originalPrice > 0 && productForm.price > 0) {
      productForm.saved = productForm.originalPrice - productForm.price;
    }

    // 构建医院关联数据
    console.log("开始构建医院关联数据...");
    console.log("当前医院选项:", hospitalOptions.value);

    const hospitalsData = selectedHospitalIds.value.map((hospitalId) => {
      const hospital = hospitalOptions.value.find((h) => h.id === hospitalId);
      console.log(`医院ID ${hospitalId} 对应的医院信息:`, hospital);
      return {
        hospitalId,
        hospitalName: hospital?.name || "",
        price: productForm.price,
        originalPrice: productForm.originalPrice,
        isActive: true,
        addedTime: new Date(),
      };
    });

    console.log("构建的医院数据:", hospitalsData);

    // 验证分类ID
    console.log("验证分类ID...");
    console.log("productForm.category 类型:", typeof productForm.category);
    console.log("productForm.category 值:", productForm.category);
    console.log(
      "是否为有效的MongoDB ObjectId格式:",
      /^[0-9a-fA-F]{24}$/.test(productForm.category || "")
    );

    const submitData = {
      title: productForm.title,
      category: productForm.category || undefined, // 确保空值时发送undefined
      price: productForm.price,
      originalPrice: productForm.originalPrice || undefined,
      saved: productForm.saved || undefined,
      hospitals: hospitalsData.length > 0 ? hospitalsData : [],
      rating: productForm.rating || undefined,
      tags: productForm.tags.length > 0 ? productForm.tags : undefined,
      image: productForm.image || undefined, // 主图（向后兼容）
      images: productForm.images.length > 0 ? productForm.images : undefined, // 图片数组
      // isHot: productForm.isHot,
      viewCount: isEdit.value ? undefined : 0,
    };

    console.log("最终提交数据:", JSON.stringify(submitData, null, 2));

    if (isEdit.value) {
      // 调用更新接口
      console.log("=== 开始调用更新接口 ===");
      console.log("请求URL:", `/pccosmetic/products/${editingProductId.value}`);
      console.log("请求方法: PUT");
      console.log("请求数据:", JSON.stringify(submitData, null, 2));

      const response = (await request.put(
        `/pccosmetic/products/${editingProductId.value}`,
        submitData
      )) as any;

      console.log("=== 更新接口响应 ===");
      console.log("响应状态:", response.success);
      console.log("完整响应:", JSON.stringify(response, null, 2));

      if (response.success) {
        console.log("更新成功");
        ElMessage.success("产品更新成功");
        refreshData(); // 刷新数据但保持分页状态
        dialogVisible.value = false; // 关闭弹窗
        resetProductForm(); // 重置表单
      } else {
        console.error("更新失败 - 服务器返回错误:", response);
        ElMessage.error(response.message || "更新失败");
      }
    } else {
      // 调用创建接口
      (submitData as any).createTime = new Date().toISOString();
      const response = (await request.post(
        "/pccosmetic/products",
        submitData
      )) as any;
      if (response.success) {
        ElMessage.success("产品创建成功");
        fetchData(); // 刷新数据
        dialogVisible.value = false; // 关闭弹窗
        resetProductForm(); // 重置表单
      } else {
        ElMessage.error(response.message || "创建失败");
      }
    }
  } catch (error: any) {
    console.error("=== 提交过程中发生异常 ===");
    console.error("异常类型:", error.constructor.name);
    console.error("异常消息:", error.message);
    console.error("完整异常对象:", error);
    if (error.response) {
      console.error("HTTP响应状态:", error.response.status);
      console.error("HTTP响应数据:", error.response.data);
    }
    ElMessage.error(`提交失败: ${error.message || "未知错误"}`);
  } finally {
    submitLoading.value = false;
  }
};

// 产品表单的省市级联选择器处理（仅用于筛选医院）
const handleProductRegionChange = (value: string) => {
  if (!value) {
    hospitalFilterForm.province = "";
    hospitalFilterForm.city = "";
    // 省市为空时显示全部医院
    fetchHospitalsByRegion();
    return;
  }

  // 根据选择的值找到对应的省市名称
  const findRegionName = (selectedValue: string) => {
    for (const province of regionOptions.value) {
      if (province.value === selectedValue) {
        hospitalFilterForm.province = province.label;
        hospitalFilterForm.city = "";
        return;
      }
      if (province.children) {
        for (const city of province.children) {
          if (city.value === selectedValue) {
            hospitalFilterForm.province = province.label;
            hospitalFilterForm.city = city.label;
            return;
          }
        }
      }
    }
  };

  findRegionName(value);
  // 省市发生变化时，刷新医院列表
  fetchHospitalsByRegion();
};

// 标签相关方法
const removeTag = (index: number) => {
  productForm.tags.splice(index, 1);
};

const showTagInput = () => {
  tagInputVisible.value = true;
  nextTick(() => {
    tagInputRef.value?.focus();
  });
};

const addTag = () => {
  const value = tagInputValue.value.trim();
  if (value && !productForm.tags.includes(value)) {
    productForm.tags.push(value);
  }
  tagInputVisible.value = false;
  tagInputValue.value = "";
};

// 生命周期
onMounted(() => {
  fetchCategories();
  fetchTagOptions();
  fetchData();
  fetchHospitalsByRegion(); // 初始化医院选项数据
});

// 根据省市获取医院列表（省市为空时显示全部医院）
const fetchHospitalsByRegion = async () => {
  try {
    const params: any = { limit: 1000 };
    if (hospitalFilterForm.province) {
      params.province = hospitalFilterForm.province;
    }
    if (hospitalFilterForm.city) {
      params.city = hospitalFilterForm.city;
    }
    const res: any = await request.get("/pcorganization/hospitals", { params });
    if (res.success) {
      hospitalOptions.value = (res.data || []).map((i: any) => ({
        id: i.id,
        name: i.name,
        address: i.address,
      }));
    }
  } catch (e) {}
};

// 选择医院后联动医院列表
const handleHospitalSelect = (ids: string[]) => {
  // 清空现有医院列表
  productForm.hospitals = [];

  // 根据选中的ID创建医院对象
  ids.forEach((id) => {
    const hospital = hospitalOptions.value.find((h) => h.id === id);
    if (hospital) {
      productForm.hospitals.push({
        hospitalId: id,
        hospitalName: hospital.name,
        price: productForm.price || undefined,
        originalPrice: productForm.originalPrice || undefined,
        isActive: true,
      });
    }
  });
};

// 上传相关
const uploadHeaders = {};
const imageFileList = ref<any[]>([]);

// handleUploadSuccess 和 handleUploadError 函数已移除
// 所有上传逻辑现在都在 uploadRequest 函数中统一处理

const handleUploadExceed = () => {
  ElMessage.warning("最多只能上传9张图片");
};
const handleUploadRemove = (file: any) => {
  // 从图片数组中移除对应的图片
  const index = imageFileList.value.findIndex((item) => item.uid === file.uid);
  if (index !== -1) {
    productForm.images.splice(index, 1);

    // 如果删除的是第一张图片，更新主图
    if (index === 0 && productForm.images.length > 0) {
      productForm.image = productForm.images[0];
    } else if (productForm.images.length === 0) {
      productForm.image = "";
    }
  }

  // 触发表单验证
  productFormRef.value?.validateField("images");
};

// 图片预览
const previewDialogVisible = ref(false);
const previewImageUrl = ref("");

const handlePreview = (file: any) => {
  previewImageUrl.value = file.url;
  previewDialogVisible.value = true;
};

// 自定义上传，拼接后端完整地址（适配不同端口/代理）
const uploadRequest = async (options: any) => {
  try {
    const form = new FormData();
    form.append("file", options.file as File);

    const res: any = await request.post("/pcproductimg/upload", form, {
      headers: {
        "Content-Type": "multipart/form-data",
        ...(uploadHeaders as any),
      },
    });

    if (res && res.success && res.data?.url) {
      // 上传成功，直接在这里处理所有逻辑
      const newImageUrl = res.data.url;

      // 检测重复图片
      if (productForm.images.includes(newImageUrl)) {
        ElMessage.warning("已有该图片，请勿重复上传");
        options.onError?.(new Error("重复图片"));
        return;
      }

      // 添加到图片数组
      productForm.images.push(newImageUrl);

      // 为向后兼容，第一张图片也设置为主图
      if (productForm.images.length === 1) {
        productForm.image = newImageUrl;
      }

      // 为 el-upload 创建完整URL用于显示缩略图
      const relativeUrl = newImageUrl;
      const baseURL =
        import.meta.env.VITE_API_BASE_URL || "http://localhost:3000";
      const fullUrl = relativeUrl.startsWith("http")
        ? relativeUrl
        : `${baseURL}${relativeUrl}`;

      const fileItem = {
        name: res.data.filename || "image",
        url: fullUrl, // 使用完整URL显示缩略图
        uid: Date.now(), // Element Plus 需要 uid
        status: "success", // 确保状态为成功
      };

      // 添加到文件列表
      imageFileList.value.push(fileItem);

      // 触发表单验证
      productFormRef.value?.validateField("images");

      // 显示成功消息
      ElMessage.success(`图片上传成功 (${productForm.images.length}/9)`);

      // 通知Element Plus上传成功
      options.onSuccess?.(res);
    } else {
      // 上传失败
      const errorMsg = res?.message || "上传失败";
      ElMessage.error(errorMsg);
      options.onError?.(new Error(errorMsg));
    }
  } catch (e: any) {
    // 网络错误或其他异常
    ElMessage.error("图片上传失败");
    options.onError?.(e);
  }
};

// 获取标签选项
const fetchTagOptions = async () => {
  try {
    const res: any = await request.get("/pcproductimg/tags");
    if (res.success) {
      tagOptions.value = res.data || [];
    }
  } catch (e) {}
};

// 新增标签对话框
const newTagDialogVisible = ref(false);
const newTagName = ref("");

// 新增分类相关
const showAddCategoryDialog = ref(false);
const categorySubmitting = ref(false);
const categoryFormRef = ref();
const categoryForm = reactive({
  name: "",
});

// 分类表单验证规则
const categoryRules = {
  name: [
    { required: true, message: "请输入分类名称", trigger: "blur" },
    {
      min: 1,
      max: 50,
      message: "分类名称长度在 1 到 50 个字符",
      trigger: "blur",
    },
  ],
};

// 产品表单验证规则
const productRules = {
  title: [
    { required: true, message: "请输入产品名称", trigger: "blur" },
    {
      min: 2,
      max: 100,
      message: "产品名称长度在 2 到 100 个字符",
      trigger: "blur",
    },
  ],
  category: [{ required: true, message: "请选择产品分类", trigger: "change" }],
  price: [
    {
      required: true,
      message: "请输入产品价格",
      trigger: "blur",
      validator: (rule: any, value: any, callback: any) => {
        if (value === null || value === undefined || value === "") {
          callback(new Error("请输入产品价格"));
        } else if (value <= 0) {
          callback(new Error("产品价格必须大于0"));
        } else {
          callback();
        }
      },
    },
  ],
  images: [
    {
      required: true,
      message: "请上传产品图片",
      trigger: "change",
      validator: (rule: any, value: any, callback: any) => {
        if (!value || value.length === 0) {
          callback(new Error("请至少上传一张产品图片"));
        } else if (value.length > 9) {
          callback(new Error("最多只能上传9张图片"));
        } else {
          callback();
        }
      },
    },
  ],
};
const openNewTagDialog = () => {
  newTagName.value = "";
  newTagDialogVisible.value = true;
};
const handleCreateTag = async () => {
  const name = (newTagName.value || "").trim();
  if (!name) {
    ElMessage.warning("请输入标签名称");
    return;
  }
  try {
    const res: any = await request.post("/pcproductimg/tags", { name });
    if (res.success) {
      ElMessage.success(res.message || "创建成功");
      // 刷新下拉
      await fetchTagOptions();
      // 自动选中刚创建的标签（若未超过3个限制）
      if (!productForm.tags) productForm.tags = [];
      if (productForm.tags.length < 3 && !productForm.tags.includes(name)) {
        productForm.tags.push(name);
      }
      newTagDialogVisible.value = false;
    } else {
      ElMessage.error(res.message || "创建失败");
    }
  } catch (e) {
    ElMessage.error("创建失败");
  }
};

// 新增分类方法
const handleCancelAddCategory = () => {
  // 重置表单
  Object.assign(categoryForm, {
    name: "",
  });
  // 清除验证
  categoryFormRef.value?.clearValidate();
  showAddCategoryDialog.value = false;
};

const handleCreateCategory = async () => {
  // 表单验证
  if (!categoryFormRef.value) return;

  const valid = await categoryFormRef.value.validate().catch(() => false);
  if (!valid) return;

  categorySubmitting.value = true;

  try {
    const response = (await request.post("/pcproductimg/categories", {
      name: categoryForm.name.trim(),
    })) as any;

    if (response.success) {
      ElMessage.success(response.message || "创建分类成功");

      // 刷新分类列表
      await fetchCategories();

      // 自动选中刚创建的分类（使用分类ID）
      productForm.category = response.data._id;

      // 关闭弹窗
      handleCancelAddCategory();
    } else {
      ElMessage.error(response.message || "创建分类失败");
    }
  } catch (error: any) {
    console.error("创建分类失败:", error);
    ElMessage.error(error?.message || "创建分类失败");
  } finally {
    categorySubmitting.value = false;
  }
};
</script>

<style scoped>
.product-container {
  height: calc(
    100vh - 60px - 48px
  ); /* 减去header高度60px和content的padding 48px */
  display: flex;
  flex-direction: column;
  padding: 16px;
  overflow: hidden;
}

.page-header {
  flex-shrink: 0;
  margin-bottom: 16px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  margin: 0 0 8px 0;
  color: #303133;
}

.page-description {
  color: #606266;
  margin: 0;
}

.content-area {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 筛选容器样式 */
.filter-container {
  flex-shrink: 0;
  margin-bottom: 16px;
  padding: 16px;
  background: #ffffff;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.04);
}

.filter-form {
  display: flex;
  align-items: flex-end;
  gap: 16px;
  flex-wrap: wrap;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
  white-space: nowrap;
  min-width: 60px;
  text-align: right;
}

.filter-input {
  width: 180px;
  height: 32px;
}

.filter-select {
  width: 160px;
  height: 32px;
}

.price-range {
  display: flex;
  align-items: center;
  gap: 8px;
}

.price-input {
  width: 120px;
  height: 32px;
}

.price-divider {
  color: #909399;
  font-weight: 500;
}


.search-btn,
.reset-btn {
  height: 32px;
  padding: 0 16px;
}

.action-section {
  flex-shrink: 0;
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.action-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.action-right {
  display: flex;
  align-items: center;
}

.table-section {
  flex: 1;
  margin-bottom: 16px;
  overflow: hidden;
}

.table-section :deep(.el-table) {
  height: 100%;
}

.table-section :deep(.el-table__body-wrapper) {
  max-height: calc(100% - 40px);
  overflow-y: auto;
}

.pagination-section {
  flex-shrink: 0;
  display: flex;
  justify-content: flex-end;
  padding-top: 8px;
  border-top: 1px solid #ebeef5;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .filter-form {
    gap: 12px;
  }

  .filter-input {
    width: 150px;
  }

  .filter-select {
    width: 130px;
  }

  .price-input {
    width: 100px;
  }
}

@media (max-width: 768px) {
  .filter-container {
    padding: 12px;
  }

  .filter-form {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }

  .filter-item {
    width: 100%;
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }

  .filter-label {
    min-width: auto;
    text-align: left;
  }

  .filter-input,
  .filter-select {
    width: 100%;
  }

  .price-range {
    width: 100%;
    justify-content: space-between;
  }

  .price-input {
    flex: 1;
  }

  .price-divider {
    margin: 0 8px;
  }


  .filter-item:last-child {
    justify-content: center;
    gap: 12px;
  }

  .search-btn,
  .reset-btn {
    flex: 1;
    min-width: 100px;
  }
}

/* 医院详情样式 */
.hospital-details-container {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 12px;
  background-color: #fafafa;
}

.hospital-detail-item {
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: white;
  margin-bottom: 8px;
}

.hospital-detail-item:last-child {
  margin-bottom: 0;
}

.hospital-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.hospital-name {
  font-weight: 500;
  color: #303133;
}

.hospital-pricing {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 小屏幕平板优化 */
@media (max-width: 992px) and (min-width: 769px) {
  .action-buttons {
    justify-content: center;
  }
}

/* 产品详情样式 */
.product-detail {
  max-height: 600px;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: 24px;
}

.section-title {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  border-left: 4px solid #409eff;
  padding-left: 12px;
}

.image-container {
  display: flex;
  align-items: flex-start;
  gap: 16px;
  flex-wrap: wrap;
}

.images-container {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
  line-height: 1.4;
}

.upload-count {
  color: #409eff;
  font-weight: 500;
  margin-left: 4px;
}

.upload-trigger {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #8c939d;
  font-size: 28px;
  cursor: pointer;
  transition: color 0.3s;
}

.upload-trigger:hover {
  color: #409eff;
}

/* 隐藏达到最大数量时的上传框 */
.upload-max-reached :deep(.el-upload--picture-card) {
  display: none !important;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 30px;
  border-radius: 8px;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.rating-container {
  display: flex;
  align-items: center;
}

.dialog-footer {
  text-align: right;
}
</style>
